1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
| /* Sample code from https://www.redblobgames.com/pathfinding/a-star/ Copyright 2014 Red Blob Games <redblobgames@gmail.com>
Feel free to use this code in your own projects, including commercial projects License: Apache v2.0 <http://www.apache.org/licenses/LICENSE-2.0.html> */
#include <iostream> #include <iomanip> #include <map> #include <set> #include <array> #include <vector> #include <utility> #include <queue> #include <tuple> #include <algorithm> #include <cstdlib> #include <functional>
struct SimpleGraph { std::map<char, std::vector<char> > edges;
std::vector<char> neighbors(char id) { return edges[id]; } };
SimpleGraph example_graph{ { { 'A',{ 'B' } }, { 'B',{ 'A', 'C', 'D' } }, { 'C',{ 'A' } }, { 'D',{ 'E', 'A' } }, { 'E',{ 'B' } } } };
struct GridLocation { int x, y; };
struct SquareGrid { static std::array<GridLocation, 4> DIRS;
int width, height; std::set<GridLocation> walls;
SquareGrid(int width_, int height_) : width(width_), height(height_) {}
bool in_bounds(GridLocation id) const { return 0 <= id.x && id.x < width && 0 <= id.y && id.y < height; }
bool passable(GridLocation id) const { return walls.find(id) == walls.end(); }
std::vector<GridLocation> neighbors(GridLocation id) const { std::vector<GridLocation> results;
for (GridLocation dir : DIRS) { GridLocation next{ id.x + dir.x, id.y + dir.y }; if (in_bounds(next) && passable(next)) { results.push_back(next); } }
if ((id.x + id.y) % 2 == 0) { // aesthetic improvement on square grids std::reverse(results.begin(), results.end()); }
return results; } };
std::array<GridLocation, 4> SquareGrid::DIRS = { GridLocation{ 1, 0 }, GridLocation{ 0, -1 }, GridLocation{ -1, 0 }, GridLocation{ 0, 1 } };
// Helpers for GridLocation
bool operator == (GridLocation a, GridLocation b) { return a.x == b.x && a.y == b.y; }
bool operator != (GridLocation a, GridLocation b) { return !(a == b); }
bool operator < (GridLocation a, GridLocation b) { return std::tie(a.x, a.y) < std::tie(b.x, b.y); }
std::basic_iostream<char>::basic_ostream& operator<<(std::basic_iostream<char>::basic_ostream& out, const GridLocation& loc) { out << '(' << loc.x << ',' << loc.y << ')'; return out; }
// This outputs a grid. Pass in a distances map if you want to print // the distances, or pass in a point_to map if you want to print // arrows that point to the parent location, or pass in a path vector // if you want to draw the path. template<class Graph> void draw_grid(const Graph& graph, int field_width, std::map<GridLocation, double>* distances = nullptr, std::map<GridLocation, GridLocation>* point_to = nullptr, std::vector<GridLocation>* path = nullptr) { for (int y = 0; y != graph.height; ++y) { for (int x = 0; x != graph.width; ++x) { GridLocation id{ x, y }; std::cout << std::left << std::setw(field_width); if (graph.walls.find(id) != graph.walls.end()) { std::cout << std::string(field_width, '#').c_str(); } else if (point_to != nullptr && point_to->count(id)) { GridLocation next = (*point_to)[id]; if (next.x == x + 1) { std::cout << "> "; } else if (next.x == x - 1) { std::cout << "< "; } else if (next.y == y + 1) { std::cout << "v "; } else if (next.y == y - 1) { std::cout << "^ "; } else { std::cout << "* "; } } else if (distances != nullptr && distances->count(id)) { std::cout << (*distances)[id]; } else if (path != nullptr && find(path->begin(), path->end(), id) != path->end()) { std::cout << '@'; } else { std::cout << '.'; } } std::cout << '\n'; } }
void add_rect(SquareGrid& grid, int x1, int y1, int x2, int y2) { for (int x = x1; x < x2; ++x) { for (int y = y1; y < y2; ++y) { grid.walls.insert(GridLocation{ x, y }); } } }
SquareGrid make_diagram1() { SquareGrid grid(30, 15); add_rect(grid, 3, 3, 5, 12); add_rect(grid, 13, 4, 15, 15); add_rect(grid, 21, 0, 23, 7); add_rect(grid, 23, 5, 26, 7); return grid; }
struct GridWithWeights : SquareGrid { std::set<GridLocation> forests; GridWithWeights(int w, int h) : SquareGrid(w, h) {} double cost(GridLocation from_node, GridLocation to_node) const { return forests.find(to_node) != forests.end() ? 5 : 1; } };
GridWithWeights make_diagram4() { GridWithWeights grid(10, 10); add_rect(grid, 1, 7, 4, 9); typedef GridLocation L; grid.forests = std::set<GridLocation>{ L{ 3, 4 }, L{ 3, 5 }, L{ 4, 1 }, L{ 4, 2 }, L{ 4, 3 }, L{ 4, 4 }, L{ 4, 5 }, L{ 4, 6 }, L{ 4, 7 }, L{ 4, 8 }, L{ 5, 1 }, L{ 5, 2 }, L{ 5, 3 }, L{ 5, 4 }, L{ 5, 5 }, L{ 5, 6 }, L{ 5, 7 }, L{ 5, 8 }, L{ 6, 2 }, L{ 6, 3 }, L{ 6, 4 }, L{ 6, 5 }, L{ 6, 6 }, L{ 6, 7 }, L{ 7, 3 }, L{ 7, 4 }, L{ 7, 5 } }; return grid; }
template<typename T, typename priority_t> struct PriorityQueue { typedef std::pair<priority_t, T> PQElement; std::priority_queue<PQElement, std::vector<PQElement>, std::greater<PQElement>> elements;
inline bool empty() const { return elements.empty(); }
inline void put(T item, priority_t priority) { elements.emplace(priority, item); }
T get() { T best_item = elements.top().second; elements.pop(); return best_item; } };
template<typename Location, typename Graph> void dijkstra_search (Graph graph, Location start, Location goal, std::map<Location, Location>& came_from, std::map<Location, double>& cost_so_far) { PriorityQueue<Location, double> frontier; frontier.put(start, 0);
came_from[start] = start; cost_so_far[start] = 0;
while (!frontier.empty()) { Location current = frontier.get();
if (current == goal) { break; }
for (Location next : graph.neighbors(current)) { double new_cost = cost_so_far[current] + graph.cost(current, next); if (cost_so_far.find(next) == cost_so_far.end() || new_cost < cost_so_far[next]) { cost_so_far[next] = new_cost; came_from[next] = current; frontier.put(next, new_cost); } } } }
template<typename Location> std::vector<Location> reconstruct_path( Location start, Location goal, std::map<Location, Location> came_from ) { std::vector<Location> path; Location current = goal; while (current != start) { path.push_back(current); current = came_from[current]; } path.push_back(start); // optional std::reverse(path.begin(), path.end()); return path; }
inline double heuristic(GridLocation a, GridLocation b) { return std::abs(a.x - b.x) + std::abs(a.y - b.y); }
template<typename Location, typename Graph> void a_star_search (Graph graph, Location start, Location goal, std::map<Location, Location>& came_from, std::map<Location, double>& cost_so_far) { PriorityQueue<Location, double> frontier; frontier.put(start, 0);
came_from[start] = start; cost_so_far[start] = 0;
while (!frontier.empty()) { Location current = frontier.get();
if (current == goal) { break; }
for (Location next : graph.neighbors(current)) { double new_cost = cost_so_far[current] + graph.cost(current, next); if (cost_so_far.find(next) == cost_so_far.end() || new_cost < cost_so_far[next]) { cost_so_far[next] = new_cost; double priority = new_cost + heuristic(next, goal); frontier.put(next, priority); came_from[next] = current; } } } }
int main(int argc, const char **argv) { GridWithWeights grid = make_diagram4(); GridLocation start{ 1, 4 }; GridLocation goal{ 8, 5 }; std::map<GridLocation, GridLocation> came_from; std::map<GridLocation, double> cost_so_far; a_star_search(grid, start, goal, came_from, cost_so_far); draw_grid(grid, 2, nullptr, &came_from); std::cout << '\n'; draw_grid(grid, 3, &cost_so_far, nullptr); std::cout << '\n'; std::vector<GridLocation> path = reconstruct_path(start, goal, came_from); draw_grid(grid, 3, nullptr, nullptr, &path); return 0; }
|